package com.company;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhf
 * @date 2022/2/10
 */
/*给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
*/
public class WordBreak {

    public static void main(String[] args) {
        String s = "leetcode";
        List<String> wordDict = new ArrayList<>();
        wordDict.add("leet");
        wordDict.add("code");
        WordBreak wordBreak = new WordBreak();
        boolean b = wordBreak.wordBreak(s, wordDict);
        System.out.println(b);
    }

    //使用回溯；
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<String>(wordDict);
        //数组存放当前目标字符是否为wordDict中的字符；
        boolean[] ans = new boolean[s.length() + 1];
        ans[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (set.contains(s.substring(j,i)) && ans[j]){
                    ans[i] = true;
                    break;
                }
            }
        }
        return ans[s.length()];
    }
}
